import React, { useState, useEffect } from 'react';
import { Card, Row, Col, Statistic, DatePicker, Select, Button, Table, Space, message, Tag, Rate } from 'antd';
import { ProCard } from '@ant-design/pro-components';
import { 
  FileTextOutlined, 
  EyeOutlined, 
  LikeOutlined, 
  DownloadOutlined,
  ReloadOutlined,
  PictureOutlined,
  CalendarOutlined,
  StarOutlined 
} from '@ant-design/icons';
import { EchartsLine, EchartsColumn, EchartsPie, EchartsArea } from '@/components/Charts';
import dayjs from 'dayjs';
import { 
  getContentStatistics, 
  getContentEngagementStats, 
  getContentQualityAnalysis,
  exportStatisticsData 
} from '@/services/statisticsApi';

const { RangePicker } = DatePicker;
const { Option } = Select;

const ContentStats: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [timeRange, setTimeRange] = useState<STATISTICS.TimeRange>('month');
  const [dateRange, setDateRange] = useState<[dayjs.Dayjs, dayjs.Dayjs]>([
    dayjs().subtract(30, 'day'),
    dayjs()
  ]);
  const [statistics, setStatistics] = useState<STATISTICS.ContentStatistics | null>(null);

  // 获取统计数据
  const fetchStatistics = async () => {
    setLoading(true);
    try {
      const params: STATISTICS.StatisticsQueryParams = {
        time_range: timeRange,
        start_date: dateRange[0].format('YYYY-MM-DD'),
        end_date: dateRange[1].format('YYYY-MM-DD'),
        granularity: 'day'
      };

      const response = await getContentStatistics(params);
      if (response.code === 200) {
        setStatistics(response.data);
      } else {
        message.error(response.message || '获取内容统计数据失败');
      }
    } catch (error) {
      console.error('获取内容统计数据失败:', error);
      message.error('获取统计数据失败');
    } finally {
      setLoading(false);
    }
  };

  // 导出数据
  const handleExport = async (type: 'excel' | 'csv' | 'pdf') => {
    try {
      const params: STATISTICS.ExportParams = {
        type,
        data_type: 'content',
        time_range: timeRange,
        start_date: dateRange[0].format('YYYY-MM-DD'),
        end_date: dateRange[1].format('YYYY-MM-DD'),
        include_charts: true
      };

      await exportStatisticsData(params);
      message.success(`${type.toUpperCase()}文件导出成功`);
    } catch (error) {
      console.error('导出失败:', error);
      message.error('导出失败');
    }
  };

  useEffect(() => {
    fetchStatistics();
  }, [timeRange, dateRange]);

  // 内容浏览量趋势图配置
  const courseViewsConfig = {
    data: statistics?.content_engagement.course_views || [],
    xField: 'date',
    yField: 'value',
    smooth: true,
    color: '#1890ff',
    area: {
      style: {
        fill: 'l(270) 0:#ffffff 0.5:#7ec2f3 1:#1890ff',
      },
    },
  };

  // 轮播图点击量趋势图配置
  const bannerClicksConfig = {
    data: statistics?.content_engagement.banner_clicks || [],
    xField: 'date',
    yField: 'value',
    smooth: true,
    color: '#52c41a',
    point: {
      size: 3,
      shape: 'circle',
    },
  };

  // 活动参与度趋势图配置
  const activityParticipationsConfig = {
    data: statistics?.content_engagement.activity_participations || [],
    xField: 'date',
    yField: 'value',
    smooth: true,
    color: '#fa8c16',
    point: {
      size: 3,
      shape: 'circle',
    },
  };

  // 热门课程表格列配置
  const topCoursesColumns = [
    {
      title: '课程名称',
      dataIndex: 'title',
      key: 'title',
      width: 200,
      ellipsis: true,
    },
    {
      title: '浏览次数',
      dataIndex: 'view_count',
      key: 'view_count',
      width: 100,
      render: (count: number) => count.toLocaleString(),
    },
    {
      title: '报名人数',
      dataIndex: 'enrollment_count',
      key: 'enrollment_count',
      width: 100,
      render: (count: number) => count.toLocaleString(),
    },
    {
      title: '评分',
      dataIndex: 'rating',
      key: 'rating',
      width: 120,
      render: (rating: number) => (
        <Space>
          <Rate disabled value={rating} allowHalf />
          <span>{rating.toFixed(1)}</span>
        </Space>
      ),
    },
  ];

  // 热门轮播图表格列配置
  const topBannersColumns = [
    {
      title: '轮播图标题',
      dataIndex: 'title',
      key: 'title',
      width: 200,
      ellipsis: true,
    },
    {
      title: '点击次数',
      dataIndex: 'click_count',
      key: 'click_count',
      width: 100,
      render: (count: number) => count.toLocaleString(),
    },
    {
      title: '展示次数',
      dataIndex: 'impression_count',
      key: 'impression_count',
      width: 100,
      render: (count: number) => count.toLocaleString(),
    },
    {
      title: '点击率',
      dataIndex: 'ctr',
      key: 'ctr',
      width: 100,
      render: (ctr: number) => (
        <Tag color={ctr >= 5 ? 'green' : ctr >= 2 ? 'orange' : 'red'}>
          {ctr.toFixed(2)}%
        </Tag>
      ),
    },
  ];

  // 热门活动表格列配置
  const topActivitiesColumns = [
    {
      title: '活动名称',
      dataIndex: 'title',
      key: 'title',
      width: 200,
      ellipsis: true,
    },
    {
      title: '参与人数',
      dataIndex: 'participation_count',
      key: 'participation_count',
      width: 100,
      render: (count: number) => count.toLocaleString(),
    },
    {
      title: '浏览次数',
      dataIndex: 'view_count',
      key: 'view_count',
      width: 100,
      render: (count: number) => count.toLocaleString(),
    },
    {
      title: '转化率',
      dataIndex: 'conversion_rate',
      key: 'conversion_rate',
      width: 100,
      render: (rate: number) => (
        <Tag color={rate >= 20 ? 'green' : rate >= 10 ? 'orange' : 'red'}>
          {rate.toFixed(2)}%
        </Tag>
      ),
    },
  ];

  return (
    <div style={{ padding: '24px' }}>
      {/* 页面标题和操作栏 */}
      <ProCard
        title="内容统计"
        extra={
          <Space>
            <Select
              value={timeRange}
              onChange={setTimeRange}
              style={{ width: 120 }}
            >
              <Option value="today">今天</Option>
              <Option value="yesterday">昨天</Option>
              <Option value="week">本周</Option>
              <Option value="month">本月</Option>
              <Option value="quarter">本季度</Option>
              <Option value="year">本年</Option>
              <Option value="custom">自定义</Option>
            </Select>
            {timeRange === 'custom' && (
              <RangePicker
                value={dateRange}
                onChange={(dates) => dates && setDateRange(dates)}
                format="YYYY-MM-DD"
              />
            )}
            <Button
              icon={<ReloadOutlined />}
              onClick={fetchStatistics}
              loading={loading}
            >
              刷新
            </Button>
            <Button.Group>
              <Button
                icon={<DownloadOutlined />}
                onClick={() => handleExport('excel')}
              >
                导出Excel
              </Button>
              <Button
                icon={<DownloadOutlined />}
                onClick={() => handleExport('csv')}
              >
                导出CSV
              </Button>
              <Button
                icon={<DownloadOutlined />}
                onClick={() => handleExport('pdf')}
              >
                导出PDF
              </Button>
            </Button.Group>
          </Space>
        }
        style={{ marginBottom: 24 }}
      />

      {/* 概览统计卡片 */}
      <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
        <Col xs={24} sm={12} md={6}>
          <Card>
            <Statistic
              title="总课程数"
              value={statistics?.overview.total_courses || 0}
              prefix={<FileTextOutlined />}
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card>
            <Statistic
              title="已发布课程"
              value={statistics?.overview.published_courses || 0}
              prefix={<EyeOutlined />}
              valueStyle={{ color: '#52c41a' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card>
            <Statistic
              title="活跃轮播图"
              value={statistics?.overview.active_banners || 0}
              prefix={<PictureOutlined />}
              valueStyle={{ color: '#fa8c16' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card>
            <Statistic
              title="活跃活动"
              value={statistics?.overview.active_activities || 0}
              prefix={<CalendarOutlined />}
              valueStyle={{ color: '#722ed1' }}
            />
          </Card>
        </Col>
      </Row>

      {/* 内容互动趋势图表 */}
      <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
        <Col xs={24} lg={8}>
          <ProCard title="课程浏览量趋势" loading={loading}>
            <EchartsArea {...courseViewsConfig} height={250} />
          </ProCard>
        </Col>
        <Col xs={24} lg={8}>
          <ProCard title="轮播图点击量趋势" loading={loading}>
            <EchartsLine {...bannerClicksConfig} height={250} />
          </ProCard>
        </Col>
        <Col xs={24} lg={8}>
          <ProCard title="活动参与度趋势" loading={loading}>
            <EchartsLine {...activityParticipationsConfig} height={250} />
          </ProCard>
        </Col>
      </Row>

      {/* 热门内容排行 */}
      <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
        <Col xs={24} lg={8}>
          <ProCard title="热门课程排行" loading={loading}>
            <Table
              columns={topCoursesColumns}
              dataSource={statistics?.top_content.courses || []}
              rowKey="id"
              pagination={{
                pageSize: 8,
                showSizeChanger: false,
                showQuickJumper: false,
              }}
              size="small"
            />
          </ProCard>
        </Col>
        <Col xs={24} lg={8}>
          <ProCard title="热门轮播图排行" loading={loading}>
            <Table
              columns={topBannersColumns}
              dataSource={statistics?.top_content.banners || []}
              rowKey="id"
              pagination={{
                pageSize: 8,
                showSizeChanger: false,
                showQuickJumper: false,
              }}
              size="small"
            />
          </ProCard>
        </Col>
        <Col xs={24} lg={8}>
          <ProCard title="热门活动排行" loading={loading}>
            <Table
              columns={topActivitiesColumns}
              dataSource={statistics?.top_content.activities || []}
              rowKey="id"
              pagination={{
                pageSize: 8,
                showSizeChanger: false,
                showQuickJumper: false,
              }}
              size="small"
            />
          </ProCard>
        </Col>
      </Row>

      {/* 内容质量分析 */}
      <Row gutter={[16, 16]}>
        <Col xs={24} lg={12}>
          <ProCard title="课程评分分布" loading={loading}>
            <EchartsColumn
              data={statistics?.content_quality.course_ratings || []}
              xField="rating"
              yField="count"
              color="#52c41a"
              columnWidthRatio={0.8}
              meta={{
                rating: { alias: '评分' },
                count: { alias: '课程数量' },
              }}
              height={300}
            />
          </ProCard>
        </Col>
        <Col xs={24} lg={12}>
          <ProCard title="内容更新情况" loading={loading}>
            <div style={{ padding: '20px 0' }}>
              <Row gutter={[16, 16]}>
                <Col span={8}>
                  <Statistic
                    title="本周更新"
                    value={statistics?.content_quality.content_freshness.updated_this_week || 0}
                    valueStyle={{ color: '#52c41a' }}
                  />
                </Col>
                <Col span={8}>
                  <Statistic
                    title="本月更新"
                    value={statistics?.content_quality.content_freshness.updated_this_month || 0}
                    valueStyle={{ color: '#1890ff' }}
                  />
                </Col>
                <Col span={8}>
                  <Statistic
                    title="过期内容"
                    value={statistics?.content_quality.content_freshness.outdated_content || 0}
                    valueStyle={{ color: '#ff4d4f' }}
                  />
                </Col>
              </Row>
              <div style={{ marginTop: 40 }}>
                <EchartsPie
                  data={[
                    { type: '本周更新', value: statistics?.content_quality.content_freshness.updated_this_week || 0 },
                    { type: '本月更新', value: statistics?.content_quality.content_freshness.updated_this_month || 0 },
                    { type: '过期内容', value: statistics?.content_quality.content_freshness.outdated_content || 0 },
                  ]}
                  angleField="value"
                  colorField="type"
                  radius={0.6}
                  label={{
                    type: 'inner',
                    content: '{percentage}',
                  }}
                  height={200}
                />
              </div>
            </div>
          </ProCard>
        </Col>
      </Row>
    </div>
  );
};

export default ContentStats;
